import json
import logging.handlers
import os

import pymysql

from config import BASE_DIR


def read_json(filename, key):
    file = BASE_DIR + os.sep + 'data' + os.sep + filename
    new_list = []
    with open(file, "r", encoding='utf-8')as f:
        new = json.load(f).get(key)
        for i in new:
            new_list.append(tuple(i.values())[1:])
    return new_list


def common_assert(response, status_code=None, expect_json=None, expect_text=None):
    # 如果status_code不为空，那么就断言
    if status_code:
        assert response.status_code == status_code, "预期状态码：{} != 实际状态码：{}".format(status_code, response.status_code)
    if expect_json:
        assert expect_json in response.json().get("description"), " 实际结果：{} 不包含 预期结果：{} ".format(
            response.json().get("description"), expect_json)
    if expect_text:
        assert expect_text in response.text, "实际结果：{} 不包含 预期结果：{}".format(response.text, expect_text)


# 日志工具
class GetLog:
    log = None
    @classmethod
    def get_log(cls):
        if cls.log is None:
            # 获取日志器
            cls.log = logging.getLogger()
            # 设置入口级别
            cls.log.setLevel(logging.INFO)
            # 设置文件
            filepath = BASE_DIR + os.sep + "log" + os.sep + "p2p.log"

            tf = logging.handlers.TimedRotatingFileHandler(filename=filepath,
                                                           when="midnight",
                                                           interval=1,
                                                           backupCount=3,
                                                           encoding="utf-8")
            # 设置格式
            fm = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
            fmt = logging.Formatter(fm)
            # 将格式器添加到文件中
            tf.setFormatter(fmt)
            # 将文件添加到日志器中
            cls.log.addHandler(tf)
        return cls.log


def connect_mysql(sql):
    cann = pymysql.connect(host='121.43.169.97',
                           port=3306,
                           user='student',
                           passwd='P2P_student_2023',
                           database='czbk_member',
                           charset='utf8',
                           autocommit=True)
    my_coursor = cann.cursor()
    my_coursor.execute(sql)
    if 'select' == sql.lower().split()[0]:
        return my_coursor.fetchall()
    else:
        return my_coursor.rowcount

    my_coursor.close()
    cann.close()


if __name__ == '__main__':
    sql = 'select * from mb_member;'
    print(connect_mysql(sql))